﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ST.Common.Util.Text
{
	public class StringHelper
	{
		#region 常用正则表达式
		///// <summary>
		///// 邮箱正则
		///// </summary>
		////^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$
		////^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$
		//public static string EMAIL_REGEX = @"^[\w]+@[\w]+(.[a-z]{2,})+$";

		///// <summary>
		///// 手机号
		///// </summary>
		//public static string MOBILE_REGEX = @"^0?1[3458][0-9]{9}$";

		///// <summary>
		///// 电话号码正则
		///// </summary>
		//public static string PHONE_REGEX = @"^(\d+-)?\d+(-\d+)?$";

		///// <summary>
		///// URL正则
		///// </summary>
		////http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? 
		////@"(http|ftp|https)://[\w]+(.[\w]+)([\w-.,@?^=%&amp;:~\+#]*[\w-\@?^=%&amp;/~\+#])"
		//public static string URL_REGEX = @"^(ftp|http|https)://\w+[\w-.]+(\w/)?";

		///// <summary>
		///// 汉字正则
		///// </summary>
		//public static string CHINESE_REGEX = @"[\u4e00-\u9fa5]";
		//public static string CHINESE_AND_WORD_REGEX = @"[\u4e00-\u9fa5a-zA-Z0-9]";
		//public static string NOT_CHINESE_OR_WORD_REGEX = @"[^\u4e00-\u9fa5a-zA-Z0-9]";
		//public static string CHINESE_ALL_REGEX = @"^[\u4e00-\u9fa5]+$";
		#endregion

		#region 去除脚本
		/// <summary>
		/// 删除html脚本
		/// </summary>
		/// <param name="Htmlstring"></param>
		/// <returns></returns>
		public static string StripTag(string Htmlstring)
		{
			//删除脚本
			Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
			//删除HTML
			Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

			Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

			Htmlstring.Replace("<", "");
			Htmlstring.Replace(">", "");
			//Htmlstring.Replace("\r\n", "");

			//Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

			return Htmlstring;
		}

		/// <summary>
		/// 去除危险脚本
		/// </summary>
		/// <param name="html"></param>
		/// <returns></returns>
		public static string StripDangerTag(string html)
		{
			html = Regex.Replace(html, @"<script[\s\S]+</script *>", "", RegexOptions.IgnoreCase);//滤除script引用和区块
			string pattern = @"(?<ScriptAttr>on\w+=\s*(['""\s]?)([/s/S]*[^\1]*?)\1)[\s|>|/>]";//去除标签中的script属性
			Regex r = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
			foreach (Match m in r.Matches(html))
			{
				string attrs = m.Groups["ScriptAttr"].Value;
				if (!string.IsNullOrEmpty(attrs))
				{
					html = html.Replace(attrs, string.Empty);
				}
			}
			html = Regex.Replace(html, @" href[ ^=]*=\s*(['""\s]?)[\w]*script+?:([/s/S]*[^\1]*?)\1[\s]*", "", RegexOptions.IgnoreCase);//滤除包含script的href
																																	   //html = Regex.Replace(html, @" src *=\s*(['""\s]?)[^\.]+\.(\w+)\1[\s]*", "", RegexOptions.IgnoreCase);//滤除src
			html = Regex.Replace(html, @"<object[\s\S]+</object *>", "", RegexOptions.IgnoreCase);//过滤object
			html = Regex.Replace(html, @"<iframe[\s\S]+</iframe *>", "", RegexOptions.IgnoreCase);//过滤Iframe
			html = Regex.Replace(html, @"<frameset[\s\S]+</frameset *>", "", RegexOptions.IgnoreCase);//过滤Frameset
			return html;
		}
		#endregion

		#region 图片提取
		/// <summary>
		/// 从html标记中提取出所有img标签中的图片地址
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static List<string> ExtractImgAll(string str)
		{
			List<string> imgs = new List<string>();
			if (string.IsNullOrEmpty(str))
			{
				return null;
			}
			string imgRegex = "<\\s*img(\\s+\\w+=['\"]+[^<]+['\"]+\\s+)*\\s*src=\\s*['\"]+([^<'\"]+)['\"]+[^<]*/?\\s*>";
			Regex regex = new Regex(imgRegex, RegexOptions.IgnoreCase);
			foreach (Match m in regex.Matches(str))
			{
				imgs.Add(m.Groups[2].Value);
			}
			return imgs;
		}
		#endregion

		#region 转换
		public static string GetStringFromArray(List<object> list)
		{
			StringBuilder buf = new StringBuilder();
			foreach (object obj in list)
			{
				buf.Append(Convert.ToString(obj) + ",");
			}
			return buf.ToString().TrimEnd(',');
		}

		/// <summary>
		/// 将字符串转为16进制字符，允许中文
		/// BitConverter.ToString(Encoding.UTF8.GetBytes("中国"))
		/// </summary>
		/// <param name="s"></param>
		/// <param name="encode"></param>
		/// <returns></returns>
		public static string StringToHexString(string s, Encoding encode)
		{
			byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
			string result = string.Empty;
			for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符
			{
				result += Convert.ToString(b[i], 16);
			}
			return result;
		}

		/// <summary>
		/// 将16进制字符串转为字符串
		/// </summary>
		/// <param name="hs"></param>
		/// <param name="encode"></param>
		/// <returns></returns>
		public static string HexStringToString(string hs, Encoding encode)
		{
			string strTemp = "";
			byte[] b = new byte[hs.Length / 2];
			for (int i = 0; i < hs.Length / 2; i++)
			{
				strTemp = hs.Substring(i * 2, 2);
				b[i] = Convert.ToByte(strTemp, 16);
			}
			//按照指定编码将字节数组变为字符串
			return encode.GetString(b);
		}

		/// <summary>
		/// 将byte[]转为16进制字符串
		/// </summary>
		/// <param name="bytes"></param>
		/// <returns></returns>
		public static string BytesToHexStr(byte[] bytes)
		{
			//string returnStr = "";
			//if (bytes != null)
			//{
			//    for (int i = 0; i < bytes.Length; i++)
			//    {
			//        returnStr += bytes[i].ToString("X2");
			//    }
			//}
			//return returnStr;
			return BitConverter.ToString(bytes).Replace("-", "");
		}

		/// <summary>
		/// 将16进制的字符串转为byte[]
		/// </summary>
		/// <param name="hexString"></param>
		/// <returns></returns>
		public static byte[] HexStrToBytes(string hexString)
		{
			if (hexString.Length == 0 || hexString.Length % 2 != 0)
			{
				return null;
			}
			byte[] bytesRet = new byte[hexString.Length / 2];
			for (int i = 0; i < bytesRet.Length; i++)
			{
				bytesRet[i] = BitConverter.GetBytes(Convert.ToInt16(hexString.Substring(2 * i, 2), 16))[0];
			}
			return bytesRet;

			//hexString = hexString.Replace(" ", "");
			//if ((hexString.Length % 2) != 0)
			//    hexString += " ";
			//byte[] returnBytes = new byte[hexString.Length / 2];
			//for (int i = 0; i < returnBytes.Length; i++)
			//    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
			//return returnBytes;
		}
		#endregion
	}
}
